package com.icode.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.icode.common.utils.R;
import com.icode.gulimall.cart.feign.ProductFeignService;
import com.icode.gulimall.cart.interceptor.CartInterceptor;
import com.icode.gulimall.cart.service.CartService;
import com.icode.gulimall.cart.to.UserInfoTo;
import com.icode.gulimall.cart.vo.CartItemVo;
import com.icode.gulimall.cart.vo.CartVo;
import com.icode.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.icode.common.constant.CartConstant.CART_PREFIX;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2021-01-09 12:18
 */

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 获取购物车，如果是登录状态，就合并临时购物车，如果未登录就返回临时购物车
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {

        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.loginUser.get();
        //不管是否登陆都会拿到临时购物车
        String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();

        //判断是否有是登陆
        if (!StringUtils.isEmpty(userInfoTo.getUserId())) {
            //登陆
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //准备合并购物车
            List<CartItemVo> tempItemList = getCartItems(tempCartKey);
            if (!CollectionUtils.isEmpty(tempItemList)) {
                for (CartItemVo cartItemVo : tempItemList) {
                    addToCart(cartItemVo.getSkuId(), cartItemVo.getCount());
                }
                //清空redis临时购物车
                clearCart(tempCartKey);
            }
            //获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        } else {
            //未登陆,直接拿到临时购物车
            List<CartItemVo> cartItems = getCartItems(tempCartKey);
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }

    /**
     * 获取购物车项信息
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String redisValue = (String) cartOps.get(skuId.toString());

        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);

        return cartItemVo;
    }

    /**
     * 改变购物项内的sku数量
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public void changeCartItemNum(Long skuId, Integer num) {
        //通过skuId获取购物项
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        cartItem.setCheck(true);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //序列化存入redis中
        String cartItemJson = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), cartItemJson);
    }

    /**
     * 删除指定sku商品
     * @param skuIds
     */
    @Override
    public void deleteItem(List<Long> skuIds) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        skuIds.stream().forEach(item->{
            cartOps.delete(item.toString());
        });
    }

    @Override
    public void changeCartItemCheck(Long skuId, Integer check) {
        //通过skuId获取购物项
        CartItemVo cartItem = getCartItem(skuId);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartItem.setCheck(check == 1);
        //序列化存入redis中
        String cartItemJson = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), cartItemJson);
    }

    @Override
    public List<CartItemVo> getCheckedItems() {
        //先得到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.loginUser.get();
        String cartKey = CART_PREFIX + userInfoTo.getUserId();

        //至少会有一件商品
        List<CartItemVo> cartItems = getCartItems(cartKey);
        List<CartItemVo> itemVoList = cartItems.stream().filter(item -> item.getCheck()).collect(Collectors.toList());

        //更新商品价格
        List<Long> skuIds = itemVoList.stream().map(CartItemVo::getSkuId).collect(Collectors.toList());
        R skuPriceInfo = productFeignService.getSkuPriceInfo(skuIds);
        if (skuPriceInfo.getCode() == 0){
            Map<Long, BigDecimal> skuPriceInfoData = skuPriceInfo.getData(new TypeReference<Map<Long, BigDecimal>>() {
            });
            itemVoList.stream().forEach(item->{
                item.setPrice(skuPriceInfoData.get(item.getSkuId()));
            });
        }

        return itemVoList;
    }

    /**
     * 清除购物车
     * @param cartKey
     */
    private void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**
     * 添加购物车项
     *
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public void addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        //判断Redis是否有该商品的信息
        String productRedisValue = (String) cartOps.get(skuId.toString());
        //如果没有就添加数据
        if (StringUtils.isEmpty(productRedisValue)) {
            CartItemVo cartItemVo = new CartItemVo(skuId, num);
            //远程调用获取sku信息
            CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0) {
                    SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                    cartItemVo.setPrice(skuInfo.getPrice());
                    cartItemVo.setTitle(skuInfo.getSkuTitle());
                }
            }, executor);

            CompletableFuture<Void> skuAttrFuture = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);
            CompletableFuture.allOf(skuInfoFuture, skuAttrFuture).get();
            //添加到redis的数据
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson);
        } else {
            //购物车有此商品，修改数量即可
            CartItemVo cartItemVo = JSON.parseObject(productRedisValue, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            //修改redis的数据
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson);
        }
    }

    /**
     * 根据cartKey获取redis中的购物车
     * @param cartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String cartKey) {

        BoundHashOperations<String, Object, Object> tempCart = redisTemplate.boundHashOps(cartKey);
        List<Object> values = tempCart.values();
        if (!CollectionUtils.isEmpty(values)) {
            List<CartItemVo> cartItemVoStream = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItemVo cartItem = JSON.parseObject(str, CartItemVo.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItemVoStream;
        }
        return null;
    }

    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //先得到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.loginUser.get();

        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //gulimall:cart:1
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        //绑定指定的key操作Redis
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);

        return operations;
    }

}
